/**
 * Created by Administrator on 2017/10/11.
 */

let userDao = require('../mysql/userDao.js');
let taskDao = require('../mysql/taskDao.js');
let mailDao = require('../mysql/mailDao.js');
let mailGotDao = require('../mysql/mailGotDao.js');
let timesDao = require('../mysql/timesDao.js');
let loginDao = require('../mysql/loginDao.js');
let advanceDao = require('../mysql/advanceDao.js');
let bluedSDK = require('../util/bluedSDK.js');
let util = require('../util/util.js');
let msg = require('../util/msg.js');
let rpc = require('../util/rpc.js');
let gameData = require('../util/gameData.js');
require('../util/prototype.js');

module.exports = enter;

function enter(cid, uuid, token) {
    this._cid = cid;
    this._uuid = uuid;
    this._blued = {};
    this._weixin = {};
    this._userModel = null;
    this._taskData = null;
    this._load = {};
    this.token(token);
}

enter.prototype.token = function (token) {
    let _this = this;
    let userModel = new userDao();
    userModel.inToken(token, function (err, res) {
        if (res == null) {
            msg.send(_this._cid, _this._uuid, 'error', {'api': 'enterToken', 'code': 10014});
            return false;
        }
        _this._userModel = userModel;
        _this.gotMail();
    });
};

enter.prototype.gotMail = function () {
    let _this = this;
    advanceDao.init().table('mailgot').pluck('mailId').wheres('userId', '=', _this._userModel.data.id).get(function (err, res) {
        let time = Math.floor(Date.now() / 1000);
        let mailIds = [];
        if (res.length > 0) {
            for (let i in res) {
                mailIds.push(res[i].mailId);
            }
        }
        advanceDao.init().table('mailbox').wheres('timeStart', '<=', time).wheres('timeEnd', '>=', time).get(function (err1, res1) {
            if (res1.length > 0) {
                for (let j in res1) {
                    if (mailIds.indexOf(res1[j].id) >= 0) {
                        continue;
                    }
                    let userId = [];
                    if (res1[j].userId) {
                        userId = JSON.parse(res1[j].userId);
                    }
                    if (userId.length > 0 && userId.indexOf(_this._userModel.data.id.toString()) < 0) {
                        continue;
                    }
                    let mailGotModel = new mailGotDao();
                    mailGotModel.set('userId', _this._userModel.data.id);
                    mailGotModel.set('mailId', res1[j].id);
                    mailGotModel.save();
                    let mailModel = new mailDao();
                    mailModel.set('userId', _this._userModel.data.id);
                    mailModel.set('type', 0);
                    mailModel.set('source', '系统');
                    mailModel.set('avatar', '');
                    mailModel.set('time', time);
                    mailModel.set('text', res1[j].text);
                    for (let k = 1; k <= 3; k++) {
                        mailModel.set('attachment' + k, res1[j]['attachment' + k]);
                        mailModel.set('amount' + k, res1[j]['amount' + k]);
                    }
                    mailModel.save();
                }
            }
            _this.run();
        });
    });
};

enter.prototype.run = function () {
    let _this = this;
    this.daily(function (daily) {
        if (daily) {
            _this.reUser();
            _this.reTask();
        } else {
            _this.task();
        }
        _this.weixin(); 
        _this.blued();
    });
};

enter.prototype.daily = function (cb) {
    let _this = this;
    let loginModel = new loginDao();
    loginModel.inToDay(_this._userModel.data.id, new Date().Format("yyyy-MM-dd"), function (err, res) {
        if (err || res) {
            cb(false);
            return false;
        }
        loginModel.set('userId', _this._userModel.data.id);
        loginModel.set('date', new Date().Format("yyyy-MM-dd hh:mm:ss"));
        loginModel.save(function () {
            cb(true);
            return true;
        });
    });
};

enter.prototype.reUser = function () {
    let _this = this;
    _this._userModel.set('tradeGold', 0);
    _this._userModel.save(function () {
        _this._load.reUser = true;
        _this.output();
    });
};

enter.prototype.task = function () {
    let _this = this;
    advanceDao.init().table('task').pluck('taskId', 'num', 'finish')
        .wheres('userId', '=', _this._userModel.data.id).get(function (err, res) {
        //if (err !== null) {
        //    return false;
        //} else if (res.length == 0) {
        //    return false;
        //} else {
        let data = {};
        if (res.length > 0) {
            for (let i in res) {
                data[res[i].taskId] = {'num': res[i].num, 'finish': res[i].finish};
            }
        }
        _this._taskData = data;
        _this._load.reUser = true;
        _this._load.task = true;
        _this.output();
        //}
    });
};

enter.prototype.reTask = function () {
    let _this = this;
    let now = util.timeStamp();
    advanceDao.init().table('task').wheres('userId', '=', _this._userModel.data.id).delete(function () {
        let taskIds = [];
        let randTaskTables = {};
        for (let i in gameData.d.task) {
            if (!gameData.d.task[i].fixed) {
                continue;
            }
            taskIds.push(gameData.d.task[i].id);
        }
        let loss = gameData.d.config.dailyTaskAmount - taskIds.length;
        if (loss > 0) {
            for (let i in gameData.d.task) {
                if (gameData.d.task[i].fixed) {
                    continue;
                }
                randTaskTables[gameData.d.task[i].id] = gameData.d.task[i].rate;
            }
            while (true) {
                let key = util.roundTable(randTaskTables);
                taskIds.push(key);
                delete randTaskTables[key];
                if (gameData.d.config.dailyTaskAmount - taskIds.length <= 0) {
                    break;
                }
            }
        }
        let data = {};
        let len = taskIds.length;
        let j = 0;
        for (let i in taskIds) {
            data[taskIds[i]] = {'num': 0, 'finish': 0};
            let taskModel = new taskDao();
            taskModel.set('userId', _this._userModel.data.id);
            taskModel.set('taskId', taskIds[i]);
            taskModel.set('num', 0);
            taskModel.set('finish', 0);
            taskModel.set('time', now);
            taskModel.save(function (err, res) {
                j++;
                if (j >= len) {
                    _this._taskData = data;
                    _this._load.task = true;
                    _this.output();
                }
            });
        }
    });
};

enter.prototype.blued = function () {
    let _this = this;
    if (_this._userModel.data.bluedId) {
        rpc.dc.send('getBlued', {'uid': _this._userModel.data.bluedId}, function (data) {
            _this._blued.platform = data.platform;
            _this._blued.accessToken = data.accessToken;
            _this._load.blued = true;
            _this.output();
        });
    } else {
        _this._load.blued = true;
        _this.output();
    }
};

enter.prototype.weixin = function () {
    let _this = this;
    if (_this._userModel.data.weixinId) {
        rpc.dc.send('getWeixin', {'uid': _this._userModel.data.weixinId}, function (data) {
            _this._weixin.platform = data.platform;
            _this._weixin.accessToken = data.accessToken;
            _this._load.weixin = true;
            _this.output();
        });
    } else {
        _this._load.weixin = true;
        _this.output();
    }
};

enter.prototype.ranking = function (cb) {
    let _this = this;
    if (_this._blued.accessToken) {
        //_this.allRankList(function (rank) {
        //    _this.giftList(rank, cb);
        //});
        bluedSDK.friends(_this._blued.accessToken, _this._userModel.data.bluedId, function (res3) {
            let uidList = [];
            console.log(res3);
            for (let i in res3.data) {
                uidList.push(res3.data[i].uid);
            }
            if (uidList.length <= 0) {
                return false;
            }
            _this.friendRankList(uidList, function (rank) {
                _this.giftList(rank, cb);
            });
        });
    } else {
        if (!gameData.d.config.touristLogin) {
            return false;
        }
        _this.allRankList(function (rank) {
            _this.giftList(rank, cb);
        });
    }
};

enter.prototype.friendRankList = function (uidList, cb) {
    advanceDao.init().table('user').pluck('id', 'name', 'avatar', 'playVictory', 'playWins')
        .limit(15).orders('playWins', 'DESC').ranking(uidList, function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            cb(res);
        }
    });
};

enter.prototype.allRankList = function (cb) {
    advanceDao.init().table('user').pluck('id', 'name', 'avatar', 'playVictory', 'playWins')
        .wheres('id', '!=', this._userModel.data.id).limit(15).orders('playWins', 'DESC').get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            cb(res);
        }
    });
};

enter.prototype.giftList = function (rank, cb) {
    let date = new Date().Format("yyyy-MM-dd");
    advanceDao.init().table('gift').pluck('userId')
        .wheres('sourceId', '=', this._userModel.data.id).wheres('date', '=', date).get(function (err, res) {
        if (err !== null) {
            cb(rank);
            return false;
        } else if (res.length == 0) {
            cb(rank);
            return false;
        }
        let ids = [];
        for (let i in res) {
            ids.push(res[i].userId);
        }
        for (let i in rank) {
            if (ids.indexOf(rank[i].id) >= 0) {
                rank[i].gift = true;
            } else {
                rank[i].gift = false;
            }
        }
        cb(rank);
    });
};

enter.prototype.times = function (cb) {
    let _this = this;
    let timesModel = new timesDao();
    timesModel.inId(_this._userModel.data.id, function (err, res) {
        if (!res) {
            timesModel.isInsert();
            timesModel.set('id', _this._userModel.data.id);
            timesModel.set('date', '2017-01-01');
            timesModel.set('signIn', 0);
            timesModel.set('signInState', 0);
            timesModel.set('loserSupport', 0);
            timesModel.set('online', 0);
            timesModel.set('onlineNum', 0);
            timesModel.set('onlineTime', (Date.now() / 1000));
            timesModel.save(function () {
                _this.timesData(timesModel.data, cb);
            });
        } else {
            let date = new Date();
            let ymd = date.Format("yyyy-MM-dd");
            let dateR = new Date(res.res.date);
            let ymdR = dateR.Format('yyyy-MM-dd');
            if (ymd != ymdR) {
                if (parseInt(Math.abs(date - dateR) / 1000 / 60 / 60 / 24) > 1) {
                    timesModel.set('signIn', 0);
                }
                timesModel.set('date', ymd);
                timesModel.set('loserSupport', 0);
                timesModel.set('online', 0);
                timesModel.set('onlineNum', 0);
                timesModel.set('signInState', 0);
            }
            timesModel.set('onlineTime', (Date.now() / 1000));
            timesModel.save(function () {
                _this.timesData(timesModel.data, cb);
            });
        }
    });
};

enter.prototype.timesData = function (data, cb) {
    let enterTimes = {};
    if (data.signInState == 0) {
        enterTimes.signIn = data.signIn;
    }
    if (gameData.d.onlineReward[data.onlineNum]) {
        let online = (gameData.d.onlineReward[data.onlineNum].minute * 60) - data.online;
        enterTimes.online = (online > 0) ? online : 0;
    }
    enterTimes.loserSupport = gameData.d.loserSupport.length - data.loserSupport;
    cb(enterTimes);
};

enter.prototype.chip = function (cb) {
    let _this = this;
    advanceDao.init().table('chip').wheres('userId', '=', _this._userModel.data.id).get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            let data = {};
            for (let i in res) {
                data[res[i].chipId] = res[i].num;
            }
            cb(data);
        }
    });
};

enter.prototype.package = function (cb) {
    let _this = this;
    let time = Math.floor(Date.now() / 1000);
    advanceDao.init().table('package').wheres('userId', '=', _this._userModel.data.id).get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            for (let i in res) {
                res[i] = util.itemInfo(res[i], time);
            }
            cb(res);
        }
    });
};
enter.prototype.notice = function (cb) {
    let now = Date.now() / 1000;
    let noticeList = [];
    for (let i in gameData.d.notice) {
        if (gameData.d.notice[i].startTime > now || gameData.d.notice[i].endTime < now) {
            continue;
        }
        if (gameData.d.notice[i].type == 0) {
            noticeList.push({'text': gameData.d.notice[i].content, 'sort': gameData.d.notice[i].sort});
        } else {
            noticeList.push({'url': gameData.d.notice[i].content, 'sort': gameData.d.notice[i].sort});
        }
    }
    noticeList.sort(function (a, b) {
        return b.sort - a.sort;
    });
    for (let i in noticeList) {
        delete noticeList[i].sort;
    }
    cb(noticeList);
};
enter.prototype.output = function () {
    if (!this._load.reUser) {
        return false;
    }
    if (!this._load.task) {
        return false;
    }
    if (!this._load.weixin) {
        return false;
    }
    let _this = this;
    msg.broadcast(_this._uuid, 'enterKick', {'id': _this._userModel.data.id});
    let loginData = {
        'id': _this._userModel.data.id,
        'bluedId': _this._userModel.data.bluedId,
        'name': _this._userModel.data.name,
        'gold': _this._userModel.data.gold,
        'score': _this._userModel.data.score,
        'gem': _this._userModel.data.gem,
        'card': _this._userModel.data.card,
        'tradeGold': _this._userModel.data.tradeGold,
        'avatar': _this._userModel.data.avatar,
        'playTimes': _this._userModel.data.playTimes,
        'playVictory': _this._userModel.data.playVictory,
        'playWins': _this._userModel.data.playWins,
        'gameId': _this._userModel.data.gameId,
        'weixinId': _this._userModel.data.weixinId,
        'serverTime': (new Date().getTime())
    };
    if (_this._blued.platform) {
        loginData.platform = _this._blued.platform;
    }
    if (_this._blued.accessToken) {
        loginData.accessToken = _this._blued.accessToken;
    }
    if (_this._weixin.platform) {
        loginData.platform = _this._weixin.platform;
    }
    if (_this._weixin.accessToken) {
        loginData.accessToken = _this._weixin.accessToken;
    }   
    console.log("enter.prototype.output>>>>");
    console.log(_this._weixin);
    console.log(loginData);
    msg.send(_this._cid, _this._uuid, 'enterLogin', loginData);
    msg.send(_this._cid, _this._uuid, 'enterTask', _this._taskData);
    _this.ranking(function (res2) {
        msg.send(_this._cid, _this._uuid, 'enterRanking', {'rank': res2});
    });
    _this.times(function (res3) {
        msg.send(_this._cid, _this._uuid, 'enterTimes', res3);
    });
    _this.chip(function (res4) {
        msg.send(_this._cid, _this._uuid, 'enterChip', res4);
    });
    let role = [];
    role.push({'roleId': 500003, 'use': true});
    msg.send(_this._cid, _this._uuid, 'enterRole', role);
    let activity = {};
    for (let i in gameData.d.activity) {
        activity[gameData.d.activity[i].key] = Boolean(gameData.d.activity[i].state);
    }
    msg.send(_this._cid, _this._uuid, 'enterActivity', activity);
    //_this.package(function (res3) {
    //    msg.send(_this._cid, _this._uuid, 'enterPackage', res3);
    //});
    _this.notice(function (res5) {
        msg.send(_this._cid, _this._uuid, 'enterNotice', res5);
    });
};